package com.android.lovely.framework

import android.graphics.Bitmap
import android.os.Bundle
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import androidx.core.view.isVisible
import com.android.lovely.databinding.ActivityWebBinding
import com.kotlin.extensions.view.ViewExt.clickable

/**
 * 自定义的网页展示活动类
 * @author why
 * @date 2025/3/8 01:28
 */
class BaseWebActivity : BaseActivity<ActivityWebBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.title.text = intent.getStringExtra("title")
        mBinding.back.clickable { onBackPressedDispatcher.onBackPressed() }
        val targetUrl = intent.getStringExtra("url").orEmpty()
        val webConfig = mBinding.webview.settings
        webConfig.setSupportZoom(true)
        webConfig.javaScriptEnabled = true
        webConfig.loadWithOverviewMode = true
        webConfig.loadsImagesAutomatically = true
        webConfig.cacheMode = WebSettings.LOAD_NO_CACHE
        mBinding.webview.webViewClient = CustomWebPageClient(mBinding.progressBar)
        mBinding.webview.webChromeClient = CustomWebProgressClient(mBinding.progressBar)
        mBinding.webview.loadUrl(targetUrl)
    }

    private class CustomWebProgressClient(private val progressIndicator: ProgressBar) : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            if (newProgress > progressIndicator.progress) {
                progressIndicator.progress = newProgress
            }
            if (newProgress == 100) {
                progressIndicator.isVisible = false
            }
        }
    }

    private class CustomWebPageClient(private val progressIndicator: ProgressBar) : WebViewClient() {
        @Deprecated("Deprecated in Java")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            progressIndicator.isVisible = true
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            progressIndicator.isVisible = false
        }
    }

}
